package cn.fanyamin.web.struts;


import java.sql.Timestamp;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.validator.LazyValidatorForm;

import cn.fanyamin.business.TaskService;
import cn.fanyamin.domain.UserCategory;
import cn.fanyamin.domain.Task;
import cn.fanyamin.domain.User;

public class ProjectAction extends SecureBaseAction {
	private static Log logger = LogFactory.getLog(TaskAction.class);

	public ActionForward list(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) {
	    
	    int taskType = NumberUtils.toInt(request.getParameter("taskType"));
	    
	    TaskService taskService = getWebApp().getTaskService();
        User user = getUserFromSession(request);
	    List<Task> taskList = null;
	    
	    if(taskType==4) {
	        taskList = taskService.getFinishedTasks(user.getUserID());
	    } else if(taskType > 0) {
	        taskList = taskService.getTaskList(taskType, user.getUserID());
	    } else {
		    taskList = taskService.list(user.getUserID());
	    }
	    
	    request.setAttribute("taskList", taskList);
		logger.info("taskList: " + taskList);
		
		setCategories(request, UserCategory.CATEGORY_TYPE_TASK);
		setContexts(request);
		
		if(taskType == Task.TASKTYPE_ONSCHEDULE) {
		    return mapping.findForward("calendar");
		} else if(taskType == 4) {
            return mapping.findForward("oldtask");
        }
        return mapping.findForward("list");

	}
	
	public ActionForward find(ActionMapping mapping, ActionForm form,
	                          HttpServletRequest request,
                              HttpServletResponse response) {

        TaskService taskService = getWebApp().getTaskService();
        User user = getUserFromSession(request);
        Task task = this.getTaskFromForm(form);
        task.setUserID(user.getUserID());
        
       
        List<Task> taskList = taskService.findTasks(task);
        
        request.setAttribute("taskList", taskList);
        request.setAttribute("foundTask", task);
        
        logger.info("taskList: " + taskList);
        
        setCategories(request, UserCategory.CATEGORY_TYPE_TASK);
        setContexts(request);

        return mapping.findForward("list");

    }
	
	public ActionForward create(ActionMapping mapping, ActionForm form,
	                            HttpServletRequest request, HttpServletResponse response) {
		TaskService taskService = getWebApp().getTaskService();
		Task task = getTaskFromForm(form);
		User user = (User)request.getSession().getAttribute("sess_user");
		if(user == null) {
		    return mapping.findForward("failure");
		}
		task.setUserID(user.getUserID());
		taskService.create(task);
		
		logger.info("create task: " + task);
		return mapping.findForward("success");
	}
	
    private Task getTaskFromForm(ActionForm form) {
		Task task = new Task();
		LazyValidatorForm taskForm = (LazyValidatorForm) form;

		task.setTaskID(NumberUtils.toInt((String) taskForm.get("taskID")));
		task.setTaskType(NumberUtils.toInt((String) taskForm.get("taskType")));
		task.setContextID(NumberUtils.toInt((String) taskForm.get("contextID")));
		task.setCategoryID(NumberUtils.toInt((String) taskForm.get("categoryID")));
		task.setEnergy(NumberUtils.toInt((String) taskForm.get("energy")));
		// BeanUtils.copyProperties(task, form);
		task.setTaskName(StringUtils.trim(""+taskForm.get("taskName")));
		task.setDuration(NumberUtils.toInt((String) taskForm
						.get("duration")));
		task.setPriority(NumberUtils.toInt((String) taskForm.get("priority")));
		task.setDescription(StringUtils.trim(""+taskForm.get("description")));

		String strDeadlline = (String) taskForm.get("deadline");
		String strCreateTime = (String) taskForm.get("createTime");
		String strBeginTime = (String) taskForm.get("beginTime");
		String strEndTime = (String) taskForm.get("endTime");

		if (StringUtils.isNotBlank(strDeadlline))
			task.setDeadline(Timestamp.valueOf(strDeadlline));
		if (StringUtils.isNotBlank(strCreateTime))
			task.setCreateTime(Timestamp.valueOf(strCreateTime));
		if (StringUtils.isNotBlank(strBeginTime))
			task.setBeginTime(Timestamp.valueOf(strBeginTime));
		if (StringUtils.isNotBlank(strEndTime))
			task.setEndTime(Timestamp.valueOf(strEndTime));
		
		//if it's repeat task, get repeat info
		
		//if it's remind task, get remind time
		
		//if it's project, get subTaskList

		return task;
	}

    public ActionForward retrieve(ActionMapping mapping, ActionForm form,
                                HttpServletRequest request, HttpServletResponse response) {
        TaskService taskService = getWebApp().getTaskService();
        LazyValidatorForm taskFrom = (LazyValidatorForm)form;
        int taskID = NumberUtils.toInt((String)taskFrom.get("taskID"));
        Task task = taskService.retrieve(taskID);
        request.setAttribute("task", task);
        
        setCategories(request, UserCategory.CATEGORY_TYPE_TASK);
        setContexts(request);
        
        return new ActionForward("/WEB-INF/jsp/struts/task/taskInfo.jsp");
    }
    
    public ActionForward update(ActionMapping mapping, ActionForm form,
                                HttpServletRequest request, HttpServletResponse response) {
        
        TaskService taskService = getWebApp().getTaskService();
        Task task = getTaskFromForm(form);
        taskService.update(task);
        logger.info("update task, task=" + task);
        return mapping.findForward("success");
    }
    
    public ActionForward delete(ActionMapping mapping, ActionForm form,
                                HttpServletRequest request, HttpServletResponse response) {
        TaskService taskService = getWebApp().getTaskService();
        LazyValidatorForm taskFrom = (LazyValidatorForm)form;
        int taskID = NumberUtils.toInt((String)taskFrom.get("taskID"));
        taskService.delete(taskID);
        logger.info("delete task, taskID=" + taskID);
        return mapping.findForward("success");
    }
    
    public ActionForward finish(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) {
		TaskService taskService = getWebApp().getTaskService();
		LazyValidatorForm taskFrom = (LazyValidatorForm) form;
		int taskID = NumberUtils.toInt((String) taskFrom.get("taskID"));
		taskService.finishTask(taskID);
		logger.info("delete task, taskID=" + taskID);
		return mapping.findForward("success");
}    
    
    public ActionForward add(ActionMapping mapping, ActionForm form,
                                HttpServletRequest request, HttpServletResponse response) {
    	logger.info("add task");
    	
    	setCategories(request, UserCategory.CATEGORY_TYPE_TASK);
    	setContexts(request);
    	
    	return mapping.findForward("add");
    }
    
    public ActionForward edit(ActionMapping mapping, ActionForm form,
                                HttpServletRequest request, HttpServletResponse response) {
        TaskService taskService = getWebApp().getTaskService();
        LazyValidatorForm taskFrom = (LazyValidatorForm)form;
        int taskID = NumberUtils.toInt((String)taskFrom.get("taskID"));
        Task task = taskService.retrieve(taskID);
        request.setAttribute("task", task);
        
        setCategories(request, UserCategory.CATEGORY_TYPE_TASK);
        setContexts(request);
        
        return mapping.findForward("edit");
    }
}
